package com.ajie.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.poi.excel.ExcelPicUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.ajie.config.annotation.RestControllerMapping;
import com.ajie.model.PageParams;
import com.ajie.model.Result;
import com.ajie.entity.Food;
import com.ajie.service.FoodService;
import com.ajie.utils.FileUtils;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.PictureData;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;

/**
 * 食物信息;(food)表控制层
 *
 * @author: ajie
 * @date : 2024-7-27
 */
@Tag(name = "食物信息")
@RestControllerMapping("/food")
@ApiSupport(author = "ajie:20999@163.com", order = 9)
public class FoodController {

    @Resource
    private FoodService foodService;

    @PostMapping("page")
    @ApiOperationSupport(order = 1)
    @Operation(summary = "分页查询")
    public Result<Page<Food>> pageQuery(@RequestBody PageParams<Food> pageParams) {
        // 1.查询参数
        Food params = pageParams.getParams();
        LambdaQueryWrapper<Food> lqw = new LambdaQueryWrapper<>();
        // 2.查询条件
        lqw.eq(params.getTitle() != null, Food::getTitle, params.getTitle());
        lqw.eq(params.getTypeId() != null, Food::getTypeId, params.getTypeId());
        // 3.分页查询
        return Result.success(foodService.page(pageParams.getPage(), lqw));
    }

    @PostMapping("insert")
    @ApiOperationSupport(order = 2)
    @Operation(summary = "新增数据")
    public Result<Boolean> insert(@RequestBody Food food) {
        if (foodService.save(food)) {
            return Result.success();
        }
        return Result.error();
    }

    @PostMapping("update")
    @ApiOperationSupport(order = 3)
    @Operation(summary = "更新数据")
    public Result<Boolean> update(@RequestBody Food food) {
        if (foodService.updateById(food)) {
            return Result.success();
        }
        return Result.error();
    }

    @GetMapping("/delete/{id}")
    @ApiOperationSupport(order = 4)
    @Operation(summary = "通过主键删除数据", parameters = {
            @Parameter(name = "id", description = "主键", required = true, in = ParameterIn.PATH)
    })
    public Result<Boolean> deleteById(@PathVariable String id) {
        if (foodService.removeById(id)) {
            return Result.success();
        }
        return Result.error();
    }

    /**
     * 在上个版本中使用
     * 1.easy-excel 导入本身不支持图片导入
     * 2.easy-poi 导入，支持图片导入
     * 3.当前版本中使用hutool工具类
     *
     * @param file
     * @return
     */
    @PostMapping("import")
    @Operation(summary = "导入excel")
    public Result<Boolean> importExcel(@RequestBody MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            return Result.error("请上传文件！");
        }
        // 根据文件流获取excel文件对象
        ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
        // 读取excel行信息并通过@Alias别名注解 实体转换为list列表
        List<Food> maps = reader.readAll(Food.class);
        // 获取excel中的图片, 得到map对象 key 图片所在位置，value图片对象
        Map<String, PictureData> picMap = ExcelPicUtil.getPicMap(reader.getWorkbook(), 0);
        picMap.forEach((key, value) -> {
            // 拿到图片所在位置
            String[] keyIndex = key.split(StrUtil.UNDERLINE);
            // 得到图片所在行
            int rowIndex = Integer.parseInt(keyIndex[0]);
            // 获取文件名后缀
            String[] fileType = value.getMimeType().split(StrUtil.SLASH);
            // 生成文件名
            String fileName = RandomUtil.randomString(32) + StrUtil.DOT + fileType[1];
            // 将图片写入磁盘
            FileUtil.writeBytes(value.getData(), FileUtils.path + fileName);
            Map<String, String> map = new HashMap<>();
            map.put("name", fileName);
            map.put("data", fileName);
            maps.get(rowIndex - 1).setImageUrls(JSONUtil.toJsonStr(Collections.singletonList(map)));
        });
        return Result.success(foodService.importExcel(maps));
    }

    @PostMapping("exports")
    public void exports(@RequestBody PageParams<Food> pageParams, HttpServletResponse response) throws IOException {
        // 1.查询参数
        Food params = pageParams.getParams();
        LambdaQueryWrapper<Food> lqw = new LambdaQueryWrapper<>();
        // 2.查询条件
        lqw.eq(params.getTitle() != null, Food::getTitle, params.getTitle());
        lqw.eq(params.getTypeId() != null, Food::getTypeId, params.getTypeId());
        // 3.分页查询
        Page<Food> page = foodService.page(pageParams.getPage(), lqw);
        List<Food> records = page.getRecords();
        ExcelWriter writer = ExcelUtil.getWriter();
        writer.setOnlyAlias(true);
        writer.write(records, true);
        writer.flush(response.getOutputStream(), true);
    }
}